const md5 = require("md5");
const DB = require("./db");
const multer = require("koa-multer");
let tools = {
  // 对数据加密
  md5(value) {
    return md5(value);
  },
  getTime() {
    return new Date();
  },
  // 获取一级分类和二级分类的信息（对数据库数据进行处理）
  getArticleData(value) {
    let firstCateArr = [];
    for (var i = 0; i < value.length; i++) {
      if (value[i].pid == "0") {
        firstCateArr.push(value[i]);
      }
    }
    for (var i = 0; i < firstCateArr.length; i++) {
      firstCateArr[i].list = [];
      for (var j = 0; j < value.length; j++) {
        if (firstCateArr[i]._id == value[j].pid) {
          firstCateArr[i].list.push(value[j]);
        }
      }
    }
    return firstCateArr;
  },
  multer() {
    let storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, "public/upload");
      },
      filename: function (req, file, cb) {
        var fileFormat = file.originalname.split(".");
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
      },
    });
    var upload = multer({ storage: storage });
    return upload;
  },
};

module.exports = tools;
